<template>
  <div class="container">
    <div class="table" v-loading="loading">
      <div ref="queryform" class="queryform">
        <div class="clearfix">
          <div class="left item">
            <label class="label-size">案件编号：</label>
            <el-input size="small" style="width:160px;" placeholder="请输入" v-model="formField.code"></el-input>
          </div>
          <div class="left item">
            <label class="label-size">案件发生时间：</label>
            <el-date-picker class="input" size="small" v-model="formField.dateRange" type="daterange"
              range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd">
            </el-date-picker>
          </div>
          <div class="right item">
            <el-button @click="resetSearch" size="small" icon="el-icon-refresh" class="default-btn">重置</el-button>
            <el-button @click="searchList" size="small" icon="el-icon-search" class="plain-btn">查询</el-button>
          </div>
        </div>
      </div>
      <div class="table-body">
        <div class="clearfix" style="margin-bottom: 10px">
          <!--          <el-button size="small" class="green-btn" @click="handleImport" :loading="importLoading"
                               v-permission="$route.path + '/Add'">{{ importLoading ? '正在导入' : '导入Excel' }}
                    </el-button>
                    <el-button size="small" class="green-btn" @click="handleImportImage" :loading="importLoading"
                               v-permission="$route.path + '/Add'">{{ importLoading ? '正在导入' : '导入图片' }}
                    </el-button>-->
          <el-button size="small" class="green-btn" @click="handleImportFile" :loading="importLoading"
            v-permission="$route.path + '/Add'">导入笔录
          </el-button>
          <input type="file" @change="importUpload" id="upLoad"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
            style="display:none;">
          <input type="file" @change="importUploadImage" id="upLoadImage" accept="image/*" style="display:none;"
            multiple="multiplt">
        </div>
        <el-table :data="tableData" :border="false" style="width: 100%">
          <!--          <el-table-column prop="name" label="案件名称"></el-table-column>-->
          <el-table-column prop="code" label="案件编号" min-width="150"></el-table-column>
          <el-table-column prop="happenedTime" label="案件发生时间" sortable></el-table-column>
          <el-table-column prop="address" label="案发地点"></el-table-column>
          <el-table-column prop="suspectName" label="嫌疑人姓名"></el-table-column>
          <!-- <el-table-column prop="suspectAge" label="嫌疑人年龄"></el-table-column> -->
          <el-table-column prop="victimName" label="受害人姓名"></el-table-column>
          <!-- <el-table-column prop="victimAge" label="受害人年龄"></el-table-column> -->
          <el-table-column prop="action" label="笔录" min-width="200">
            <template slot-scope="{ row, index }">
              <el-button size="small" type="text" @click="handleShowModal(row, 1)">嫌疑人（{{ row.suspectNoteNum || 0
                }}）</el-button>
              <el-button size="small" type="text" @click="handleShowModal(row, 2)">受害人（{{ row.victimNoteNum || 0
                }}）</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="clearfix">
          <el-pagination style="text-align: center" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" :current-page="pagination.pageIndex"
            :page-sizes="[10, 20, 30, 40, 50]" :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="pagination.total">
          </el-pagination>
        </div>
      </div>
    </div>
    <el-dialog title="笔录列表" center :visible.sync="noteVisible" :close-on-click-modal="false" @close="closeUpload"
      width="650px">
      <div class="noteTypes">
        <span :class="['item', { active: type.value === noteActive }]" @click="handleChangeNoteType(type.value)"
          v-for="type in noteTypes" :key="type.value">{{
            type.label }}</span>
      </div>
      <div class="note-list note-loading">
        <div class="cell" @click="onJumpDetail(item)" v-for="(item, index) in noteList" :key="index">
          {{ ['', '嫌疑人', '受害人'][noteActive] }}{{ item.personName }}的{{ item.interviewNumber }}笔录
        </div>
        <div class="empty-box">
          <el-empty description="暂无数据" :image-size="100" v-if="noteList && noteList.length == 0"></el-empty>
        </div>
      </div>
    </el-dialog>
    <el-dialog title="导入笔录" :visible.sync="uploadDialog" :close-on-click-modal="false" @close="closeUpload"
      width="650px">
      <div class="clearfix">
        <div class="left item">
          <label class="label-size">笔录文件：</label>
        </div>
        <div class="left">
          <el-upload class="upload-demo" drag :on-change="changeFile" :on-remove="handleRemove" :file-list="fileList"
            action="/" :auto-upload="false" v-loading="uploadLoading" element-loading-text="解析文件中...">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="tips">支持 PDF、RAR、ZIP 格式</div>
            <div class="tips">建议文件名称格式：XXXXXXXXXX_案件编号-嫌疑人/受害人-名字-第X次</div>
          </el-upload>
        </div>
      </div>
      <div class="clearfix" style="margin-top: 30px">
        <div class="left item">
          <label class="label-size">案件编号：</label>
          <el-input size="small" style="width:494px;" placeholder="文件上传后自动填充" v-model="formFile.caseCode"></el-input>
        </div>
      </div>
      <div class="clearfix">
        <div class="left item">
          <label class="label-size">嫌疑人：</label>
          <el-input size="small" style="width:190px;" v-model="formFile.suspectName"></el-input>
        </div>
        <div class="left item">
          <label class="label-size">受害人：</label>
          <el-input size="small" style="width:190px;" v-model="formFile.victimName"></el-input>
        </div>
      </div>

      <span slot="footer" class="dialogFooter">
        <el-button size="small" :disabled="uploadLoading" @click="uploadDialog = false">取 消</el-button>
        <el-button size="small" :disabled="uploadLoading" class="primary-btn" @click="UploadFile">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import table from '@/mixins/table.js'
import { sandbox } from '@/libs/util'

export default {
  mixins: [table],
  components: {},
  data() {
    return {
      formField: sandbox({
        dateRange: [],
        name: '',
        timeBegin: '',
        timeEnd: '',
      }),
      formFile: {
        caseCode: '',
        suspectName: '',
        victimName: '',
        list: []
      },
      tableData: [],
      fileList: [],
      noteList: null, //笔录列表
      uploadDialog: false,
      uploadLoading: false,
      noteVisible: false, //笔录列表弹窗显示/隐藏
      noteTypes: [
        { label: '嫌疑人', value: 1 },
        { label: '受害人', value: 2 },
      ],
      noteActive: 1, // 默认选中的笔录类型
      selItem: null, //选择的当前行
    }
  },
  methods: {
    // 跳转到
    onJumpDetail(row) {
      console.log(row);
	  //this.$router.push({path:'/ListManage/noteDetail',quary:{id:row.id,type:this.noteActive}})
      this.$router.push('/ListManage/noteDetail?id=' + row.id + "&type=" + this.noteActive + "&code=" + this.selItem.code)
    },
    // 切换笔录类型
    handleChangeNoteType(type) {
      if (this.noteActive === type) return;
      this.noteActive = type;
      this.loadNoteList();
    },
    // 显示笔录列表弹窗
    handleShowModal(row, type) {
      console.log(row);

      this.selItem = row;
      this.noteActive = type;
      this.noteVisible = true;
      this.$nextTick(() => {
        this.loadNoteList();
      })
    },
    LoadTableDataMethod() {
      this.formField.timeBegin = this.formField.dateRange?.length ? this.formField.dateRange[0] : ''
      this.formField.timeEnd = this.formField.dateRange?.length ? this.formField.dateRange[1] : ''
      return this.$api
        .api_urcap_baseInfoCase_queryPage({
          body: Object.assign(this.formField, this.pagination)
        })
        .then(res => {
          this.tableData = res.data.records
          this.pagination.currentPage = res.data.current
          this.pagination.pageSize = res.data.size
          this.pagination.total = res.data.total
        })
    },
    loadNoteList() {
      const loading = this.$loading({
        target: document.querySelector('.note-loading'),
        text: 'Loading',
        spinner: 'el-icon-loading',
      });

      this.noteList = null
      this.$api
        .api_urcap_caseNote_list({
          body: { caseCode: this.selItem.code },
          param: { noteType: ['', 'suspect', 'victim'][this.noteActive] }
        })
        .then(res => {
          loading.close();
          this.noteList = []
          if (res.code != 1000) {
            return this.$message({
              type: 'error',
              message: res.message
            })
          }
          this.noteList = res.data;
          console.log('------');
        })
    },
    importMethod(form) {
      return this.$api
        .api_urcap_baseInfoCase_upload({
          body: form
        })
    },
    handleImportImage() {
      document.getElementById('upLoadImage').value = "";
      document.getElementById('upLoadImage').click();
    },

    changeFile(file, fileList) {
      console.log('file', file)
      console.log('fileList', fileList)
      let fileNameArray = file.name.replace(/.pdf/g, '').split('-')
      if (this.formFile.caseCode && fileNameArray?.[0] !== this.formFile.caseCode) {
        this.$message({
          type: 'error',
          message: '只支持一次上传同一个案件'
        })
        return;
      }
      this.formFile.caseCode = fileNameArray[0]
      if(this.formFile.caseCode.indexOf('_') > -1) {
        let arry = this.formFile.caseCode.split('_')
        this.formFile.caseCode = arry[arry.length - 1]
      }

      if (fileNameArray[1] === '受害人') {
        this.formFile.victimName = fileNameArray?.[2]
      } else {
        this.formFile.suspectName = fileNameArray?.[2]
      }
      console.log('fileNameArray', fileNameArray)
      this.uploadLoading = true
      let form = new FormData()
      form.append('files', file.raw)
      this.$api.api_urcap_baseInfoCase_parseCasePic({
        body: form
      }).then((res) => {
        const list = res.data
        this.formFile.list = this.formFile.list.concat(list)
        this.$message({
          type: 'success',
          message: '文件解析完成'
        })
      }).finally(() => {
        this.uploadLoading = false
      })
    },

    handleRemove(file, fileList) {
      const findIndex = this.fileList.findIndex(item => item.uid === file.uid)
      this.formFile.list.splice(findIndex, 1)
      if (!this.formFile.list.length) {
        this.formFile.caseCode = ''
      }
      let victimNameList = this.formFile.list.map(item => item.victim.name)
      let suspectNameList = this.formFile.list.map(item => item.suspect.name)
      this.formFile.victimName = victimNameList.join('、')
      this.formFile.suspectName = suspectNameList.join('、')
    },
    handleImportFile() {
      this.uploadDialog = true
    },
    closeUpload() {
      this.fileList = []
      this.formFile = {
        caseCode: '',
        suspectName: '',
        victimName: '',
        list: []
      }
    },
    UploadFile() {
      if (!this.formFile?.list?.length) {
        this.$message({
          type: 'error',
          message: '未上传或解析文件无效'
        })
        return
      }
      this.$api.api_urcap_baseInfoCase_saveBatchForPyParseJson({
        body: {
          caseNumber: this.formFile.caseCode,
          suspectName: this.formFile.suspectName,
          victimName: this.formFile.victimName,
          data: JSON.stringify(this.formFile.list),
        }
      }).then((res) => {
        this.$message({
          type: 'success',
          message: '操作成功'
        })
        this.uploadDialog = false
        this.fetchData()
      }).finally(() => {
      })
    },
    importUploadImage() {
      let form = new FormData()
      let file = document.getElementById('upLoadImage');
      let files = file.files
      for (let i = 0; i < files.length; i++) {
        form.append('files', files[i])
      }

      this.importLoading = true
      this.$api.api_urcap_baseInfoCase_uploadCasePic({
        body: form
      }).then((res) => {
        this.$message({
          type: 'success',
          message: '导入成功'
        })
        this.fetchData()
      }).finally(() => {
        this.importLoading = false
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.upload-demo {
  padding: 10px 20px;
  border: 1px dashed #ccc;
}

.noteTypes {
  display: flex;
  justify-content: center;

  .item {
    width: 90px;
    padding: 5px 0;
    border-radius: 3px;
    background-color: #fff;
    text-align: center;
    border: 1px solid rgba(140, 140, 140, 1);
    cursor: pointer;

    &.active {
      background-color: #2774F4;
      color: #fff;
      border: 1px solid #2774F4;
    }

    &:first-child {
      border-right: none;
      border-radius: 3px 0 0 3px;
    }

    &:last-child {
      border-left: none;
      border-radius: 0 3px 3px 0;
    }
  }
}

.note-list {
  min-height: 200px;
  margin-top: 20px;

  .empty-box {
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
  }

  .cell {
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 10px 0;
    color: #02A7F0;
    cursor: pointer;
  }
}
</style>
